/**
 * Copyright 2021 xpstem.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.xpstem.lelink;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xpstem.lelink.bluetooth.BluetoothManager;
import com.xpstem.lelink.bluetooth.BluetoothConnection;
import com.xpstem.lelink.bluetooth.BtDeviceInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author billy zhang
 */
public class BluetoothActivity extends AppCompatActivity {

    public static final String TAG = BluetoothActivity.class.getSimpleName();

    private BluetoothManager bleManager;
    private int progress = 0;
    private TextView statusText;
    private TextView messageText;
    private ProgressBar progressBar;
    private StringBuilder stringBuilder;
    private List<BtDeviceInfo> deviceList;
    private DeviceListAdapter listAdapter;
    private RecyclerView deviceListview;
    private RelativeLayout deviceLayout;
    private RelativeLayout messageLayout;
    private BluetoothManager.OnSearchListener searchListener;
    private BluetoothConnection bleConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

        deviceList = new ArrayList<>();
        listAdapter = new DeviceListAdapter(deviceList);
        deviceLayout = (RelativeLayout)findViewById(R.id.devicelayout);
        deviceListview = (RecyclerView)findViewById(R.id.devicelistview);
        deviceListview.setLayoutManager(new LinearLayoutManager(this));
        deviceListview.setAdapter(listAdapter);

        stringBuilder = new StringBuilder();
        messageLayout = (RelativeLayout)findViewById(R.id.messagelayout);
        progressBar = (ProgressBar)findViewById(R.id.progressbar);
        messageText = (TextView)findViewById(R.id.messagetext);
        statusText = (TextView)findViewById(R.id.statustext);

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {
                    Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
                }
            }
        }
        initBlueManager();
        initLisetener();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String message = msg.obj.toString();
            switch (msg.what) {
                case 0:
                    statusText.setText(message);
                    break;
                case 1:
                    stringBuilder.append(message + " \n");
                    messageText.setText(stringBuilder.toString());
                    progress += 4;
                    progressBar.setProgress(progress);
                    break;
                case 2:
                    progress = 100;
                    progressBar.setProgress(progress);
                    break;
                case 3:
                    statusText.setText("接收完成！");
                    stringBuilder.delete(0, stringBuilder.length());
                    stringBuilder.append(message);
                    messageText.setText(stringBuilder.toString());
                    break;
                case 4:
                    messageLayout.setVisibility(View.VISIBLE);
                    deviceLayout.setVisibility(View.GONE);

                    break;
            }
        }
    };

    /**
     * 初始化蓝牙管理，设置监听
     */
    public void initBlueManager() {
        searchListener = new BluetoothManager.OnSearchListener() {
            @Override
            public void onStartDiscovery() {
                sendMessage(0, "正在搜索设备..");
                Log.d(TAG, "onStartDiscovery()");

            }

            @Override
            public void onNewDeviceFound(android.bluetooth.BluetoothDevice device) {
                Log.d(TAG, "new device: " + device.getName() + " " + device.getAddress());
            }

            @Override
            public void onSearchCompleted(List<BtDeviceInfo> bondedList, List<BtDeviceInfo> newList) {
                Log.d(TAG, "SearchCompleted: bondedList" + bondedList.toString());
                Log.d(TAG, "SearchCompleted: newList" + newList.toString());
                sendMessage(0, "搜索完成,点击列表进行连接！");
                deviceList.clear();
                deviceList.addAll( bondedList );
                deviceList.addAll( newList );
                listAdapter.notifyDataSetChanged();
                messageLayout.setVisibility(View.GONE);
                deviceLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(Exception e) {
                sendMessage(0, "搜索失败");
            }
        };

        bleManager = BluetoothManager.getInstance(this);
        bleManager.setOnSearchListener(searchListener);
        bleManager.requestEnableBt();
    }

    /**
     * 为控件添加事件监听
     */
    public void initLisetener() {

        listAdapter.setOnItemClickListener(new DeviceListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DeviceListAdapter adapter, View view, int position) {
                BtDeviceInfo info = deviceList.get(position);
                String mac = info.getAddress();
                if (info.bonded == 1) {
                    Intent intent = getIntent();
                    intent.putExtra("macAddress", mac);
                    setResult(RESULT_OK, intent);
                    finish();
                }

                if (bleConnection != null) {
                    try {
                        bleConnection.disconnect();
                        bleConnection = null;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

                bleConnection = new BluetoothConnection(getApplicationContext(), mac);
                bleConnection.setOnConnectListener(new BluetoothConnection.OnConnectListener() {
                    @Override
                    public void onConnectSuccess() {
                        try {
                            bleConnection.disconnect();
                            bleConnection = null;
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }

                        Intent intent = getIntent();
                        intent.putExtra("macAddress", mac);
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void onConnectFailed() {

                    }

                    @Override
                    public void onConnectionLost(Exception ex) {

                    }
                });
                bleConnection.connect();
            }
        });

        findViewById(R.id.searchbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bleManager.setReadVersion(false);
                bleManager.searchDevices();
            }
        });

        findViewById(R.id.cancelbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bleManager.stopSearch();
            }
        });

        findViewById(R.id.refreshbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bleManager.refresh();
            }
        });

        findViewById(R.id.closebtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (bleConnection != null) {
                        bleConnection.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                messageText.setText(null);
                deviceLayout.setVisibility(View.VISIBLE);
                messageLayout.setVisibility(View.GONE);
            }
        });
    }

    /**
     * @param type    0 修改状态  1 更新进度  2 体检完成  3 体检数据进度
     * @param context
     */
    public void sendMessage(int type, String context) {
        if (handler != null) {
            Message message = handler.obtainMessage();
            message.what = type;
            message.obj = context;
            handler.sendMessage(message);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 2) {
            if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION) && grantResults[0]
                    == PackageManager.PERMISSION_GRANTED) {
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.
                        permission.ACCESS_COARSE_LOCATION)) {
                    return;
                }
            }
        }
    }

}